package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.systembar.SystemBarHelper;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.ECContentObservers;
import com.yuntongxun.ecdemo.common.dialog.ECAlertDialog;
import com.yuntongxun.ecdemo.common.dialog.ECProgressDialog;
import com.yuntongxun.ecdemo.common.utils.CrashHandler;
import com.yuntongxun.ecdemo.common.utils.DemoUtils;
import com.yuntongxun.ecdemo.common.utils.ECNotificationManager;
import com.yuntongxun.ecdemo.common.utils.ECPreferenceSettings;
import com.yuntongxun.ecdemo.common.utils.ECPreferences;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.core.ClientUser;
import com.yuntongxun.ecdemo.core.ContactsCache;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.storage.ConversationSqlManager;
import com.yuntongxun.ecdemo.storage.IMessageSqlManager;
import com.yuntongxun.ecdemo.ui.BaseFragment;
import com.yuntongxun.ecdemo.ui.ConversationListFragment;
import com.yuntongxun.ecdemo.ui.LauncherActivity;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecdemo.ui.TabFragment;
import com.yuntongxun.ecdemo.ui.account.LoginActivity;
import com.yuntongxun.ecdemo.ui.chatting.IMChattingHelper;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.voicechat.ui.fragment.MeFragment;
import com.yuntongxun.ecdemo.voicechat.view.NoScrollViewpager;
import com.yuntongxun.ecsdk.ECChatManager;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.ecsdk.platformtools.ECHandlerHelper;

import java.io.InvalidClassException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 首页
 *
 * @author li_zhuonan
 * @version 1.0
 * @since 2016/11/24
 */

public class HomeActivity extends BaseVoiceChatFragmentActivity implements ConversationListFragment.OnUpdateMsgUnreadCountsListener{
    @InjectView(R.id.tab_pager)
    NoScrollViewpager mPager;
    @InjectView(R.id.main_bottom_tab_chats_icon)
    ImageView mainBottomTabChatsIcon;
    @InjectView(R.id.main_bottom_tab_chats_text)
    TextView mainBottomTabChatsText;
    @InjectView(R.id.main_bottom_tab_chats_layout)
    LinearLayout mainBottomTabChatsLayout;
    @InjectView(R.id.main_bottom_tab_member_icon)
    ImageView mainBottomTabMemberIcon;
    @InjectView(R.id.main_bottom_tab_member_text)
    TextView mainBottomTabMemberText;
    @InjectView(R.id.main_bottom_tab_member_layout)
    LinearLayout mainBottomTabMemberLayout;
    @InjectView(R.id.main_bottom_tab_info_icon)
    ImageView mainBottomTabInfoIcon;
    @InjectView(R.id.main_bottom_tab_info_text)
    TextView mainBottomTabInfoText;
    @InjectView(R.id.main_bottom_tab_info_layout)
    LinearLayout mainBottomTabInfoLayout;
    @InjectView(R.id.home_windows_Layout)
    RelativeLayout homeWindowsLayout;

    private MainFragmentAdapter mAdapter;

    /**
     * 当前HomeActivityUI 实例
     */
    public static HomeActivity mLauncherUI;
    /**
     * 当前ECLauncherUI实例产生个数
     */
    public static int mLauncherInstanceCount = 0;


    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_home;
    }

    @Override
    protected void initViewsAndEvents() {
        Intent intentGroup =new Intent();
        intentGroup.setAction("com.yuntongxun.ecdemo.inited");
        sendBroadcast(intentGroup);
        if (mLauncherUI != null) {
            LogUtil.i(LogUtil.getLogUtilsTag(LauncherActivity.class),
                    "finish last LauncherUI");
            mLauncherUI.finish();
        }
//		CCPAppManager.addActivityUI(mLauncherUI);
        mLauncherUI = this;
        mLauncherInstanceCount++;
        setupViews();
        initWelcome();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ECContentObservers.getInstance().initContentObserver();
    }

    private boolean mInit = false;

    private Runnable initRunnable = new Runnable() {
        @Override
        public void run() {
            mInit = false;
            initLauncherUIView();
        }
    };

    private void initWelcome() {

        Intent intentGroup =new Intent();
        intentGroup.setAction("com.yuntongxun.ecdemo.inited");
        sendBroadcast(intentGroup);

        if (!mInit) {
            mInit = true;
//            setContentView(R.layout.splash_activity);
            // 程序启动开始创建一个splash用来初始化程序基本数据
            ECHandlerHelper.postDelayedRunnOnUI(initRunnable, 500);
        }
    }

    private void initLauncherUIView() {
        Intent intent = getIntent();
        if (intent != null && intent.getIntExtra("launcher_from", -1) == 1) {
            // 检测从登陆界面过来，判断是不是第一次安装使用
            checkFirstUse();
        }

        // 如果是登陆过来的
        doInitAction();
    }

    private ECProgressDialog mPostingdialog;

    private boolean isFirstUse() {
        boolean firstUse = ECPreferences.getSharedPreferences().getBoolean(
                ECPreferenceSettings.SETTINGS_FIRST_USE.getId(),
                ((Boolean) ECPreferenceSettings.SETTINGS_FIRST_USE
                        .getDefaultValue()).booleanValue());
        return firstUse;
    }

    private void checkFirstUse() {
        boolean firstUse = isFirstUse();

        // Display the welcome message?
        if (firstUse) {
            if (IMChattingHelper.isSyncOffline()) {
                mPostingdialog = new ECProgressDialog(this,
                        R.string.tab_loading);
                mPostingdialog.setCanceledOnTouchOutside(false);
                mPostingdialog.setCancelable(false);
                mPostingdialog.show();
            }
            // Don't display again this dialog
            try {
                ECPreferences.savePreference(
                        ECPreferenceSettings.SETTINGS_FIRST_USE, Boolean.FALSE,
                        true);
            } catch (Exception e) {
                /** NON BLOCK **/
            }
        }
    }

    private boolean mInitActionFlag;
    /**
     * 处理一些初始化操作
     */
    private void doInitAction() {
        if (SDKCoreHelper.getConnectState() == ECDevice.ECConnectState.CONNECT_SUCCESS
                && !mInitActionFlag) {

//            // 检测当前的版本
//            SDKCoreHelper.SoftUpdate mSoftUpdate = SDKCoreHelper.mSoftUpdate;
//            if (mSoftUpdate != null) {
//                if (DemoUtils.checkUpdater(mSoftUpdate.version)) {
//                    boolean force = mSoftUpdate.force;
//                    showUpdaterTips(mSoftUpdate.desc , force);
//                    if (force) {
//                        return;
//                    }
//                }
//            }


            String account = getAutoRegistAccount();
            if (!TextUtils.isEmpty(account)) {
                ClientUser user = new ClientUser("").from(account);
                CCPAppManager.setClientUser(user);
            }
//            settingPersonInfo();
            IMChattingHelper.getInstance().getPersonInfo();
            // 检测离线消息
            checkOffineMessage();
            mInitActionFlag = true;
        }
    }

    /**
     * 检测离线消息
     */
    private void checkOffineMessage() {
        if (SDKCoreHelper.getConnectState() != ECDevice.ECConnectState.CONNECT_SUCCESS) {
            return;
        }
        ECHandlerHelper handlerHelper = new ECHandlerHelper();
        handlerHelper.postDelayedRunnOnThead(new Runnable() {
            @Override
            public void run() {
                boolean result = IMChattingHelper.isSyncOffline();
                if (!result) {
                    ECHandlerHelper.postRunnOnUI(new Runnable() {
                        @Override
                        public void run() {
                            disPostingLoading();
                        }
                    });
                    IMChattingHelper.checkDownFailMsg();
                }
            }
        }, 1000);
    }

    private void disPostingLoading() {
        if (mPostingdialog != null && mPostingdialog.isShowing()) {
            mPostingdialog.dismiss();
        }
    }

    private HomeActivity.InternalReceiver internalReceiver;
    /**
     * 注册广播
     *
     * @param actionArray
     */
    protected final void registerReceiver(String[] actionArray) {
        if (actionArray == null) {
            return;
        }
        IntentFilter intentfilter = new IntentFilter();
        for (String action : actionArray) {
            intentfilter.addAction(action);
        }
        if (internalReceiver == null) {
            internalReceiver = new HomeActivity.InternalReceiver();
        }
        registerReceiver(internalReceiver, intentfilter);
    }

    /**
     * 检查是否需要自动登录
     *
     * @return
     */
    private String getAutoRegistAccount() {
        SharedPreferences sharedPreferences = ECPreferences
                .getSharedPreferences();
        ECPreferenceSettings registAuto = ECPreferenceSettings.SETTINGS_REGIST_AUTO;
        String registAccount = sharedPreferences.getString(registAuto.getId(),
                (String) registAuto.getDefaultValue());
        return registAccount;
    }

    @Override
    protected boolean isEnableSwipe() {
        return false;
    }


    private void setupViews() {
//        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        mPager.setNoScroll(true);
        mPager.setOffscreenPageLimit(3);
        mAdapter = new MainFragmentAdapter(getSupportFragmentManager());
        mPager.setAdapter(mAdapter);

        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                String[] tabCount = new String[]{"Chats", "Member", "Me"};
                setTitle(tabCount[position]);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @OnClick(R.id.main_bottom_tab_chats_layout)
    public void clickTabChats(){
        mPager.setCurrentItem(0);

        initIconText(0);
    }

    @OnClick(R.id.main_bottom_tab_member_layout)
    public void clickTabMember(){

        mPager.setCurrentItem(1);

        initIconText(1);
    }

    @OnClick(R.id.main_bottom_tab_info_layout)
    public void clickTabInfo(){
        mPager.setCurrentItem(2);

        initIconText(2);
    }

    private void initIconText(int index){

        mainBottomTabChatsIcon.setImageResource(R.drawable.tab0_normal_icon1080);
        mainBottomTabChatsText.setTextColor(getResources().getColor(R.color.gray));

        mainBottomTabMemberIcon.setImageResource(R.drawable.tab1_normal_icon1080);
        mainBottomTabMemberText.setTextColor(getResources().getColor(R.color.gray));

        mainBottomTabInfoIcon.setImageResource(R.drawable.tab2_normal_icon1080);
        mainBottomTabInfoText.setTextColor(getResources().getColor(R.color.gray));

        if(index == 0){
            mainBottomTabChatsIcon.setImageResource(R.drawable.tab0_selected_icon1080);
            mainBottomTabChatsText.setTextColor(getResources().getColor(R.color.colorPrimary));
        }else if(index == 1){
            mainBottomTabMemberIcon.setImageResource(R.drawable.tab1_selected_icon1080);
            mainBottomTabMemberText.setTextColor(getResources().getColor(R.color.colorPrimary));
        }else{
            mainBottomTabInfoIcon.setImageResource(R.drawable.tab2_selected_icon1080);
            mainBottomTabInfoText.setTextColor(getResources().getColor(R.color.colorPrimary));

        }
    }

    @Override
    public void OnUpdateMsgUnreadCounts() {
        int unreadCount = IMessageSqlManager.qureyAllSessionUnreadCount();
        int notifyUnreadCount = IMessageSqlManager.getUnNotifyUnreadCount();
        int count = unreadCount;
        if (unreadCount >= notifyUnreadCount) {
            count = unreadCount - notifyUnreadCount;
        }
//        if (mPager != null) {
//            mLauncherUITabView.updateMainTabUnread(count);
//        }
    }

    public class MainFragmentAdapter extends FragmentPagerAdapter {

        private final String[] tabCount = new String[]{"Chats", "Member", "Me"};
        private int mCount = tabCount.length;

        public MainFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            BaseFragment mFragment = null;
            if (position == 0) {
                mFragment = (TabFragment) Fragment.instantiate(HomeActivity.this,
                        ConversationListFragment.class.getName(), null);
                return  mFragment;
            } else if (position == 1) {
                return new MeFragment();
            } else {
//                return InfoFragment.newInstance(tabCount[position % tabCount.length]);
                return new MeFragment();
            }

        }

        @Override
        public int getCount() {
            return mCount;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabCount[position % tabCount.length];
        }

    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class InternalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null || TextUtils.isEmpty(intent.getAction())) {
                return;
            }
            LogUtil.d("homeActivity", "[onReceive] action:" + intent.getAction());
            if (IMChattingHelper.INTENT_ACTION_SYNC_MESSAGE.equals(intent
                    .getAction())) {
                disPostingLoading();
            } else if (SDKCoreHelper.ACTION_SDK_CONNECT.equals(intent
                    .getAction())) {
                doInitAction();
                // tetstMesge();
                BaseFragment tabView = (TabFragment) Fragment.instantiate(HomeActivity.this,
                        ConversationListFragment.class.getName(), null);;
                if (tabView != null
                        && tabView instanceof ConversationListFragment) {
                    ((ConversationListFragment) tabView).updateConnectState();
                }
            } else if (SDKCoreHelper.ACTION_KICK_OFF.equals(intent.getAction())) {
                String kickoffText = intent.getStringExtra("kickoffText");
                handlerKickOff(kickoffText);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (internalReceiver != null) {
            unregisterReceiver(internalReceiver);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intentGroup =new Intent();
        intentGroup.setAction("com.yuntongxun.ecdemo.inited");
        sendBroadcast(intentGroup);

    }

    @Override
    protected void onResume() {
        LogUtil.i(LogUtil.getLogUtilsTag(LauncherActivity.class),
                "onResume start");
        super.onResume();

        Intent intentGroup =new Intent();
        intentGroup.setAction("com.yuntongxun.ecdemo.inited");
        sendBroadcast(intentGroup);

//        CrashHandler.getInstance().setContext(this);
        // 统计时长
//		MobclickAgent.onResume(this);

        boolean fullExit = ECPreferences.getSharedPreferences().getBoolean(
                ECPreferenceSettings.SETTINGS_FULLY_EXIT.getId(), false);
        if (fullExit) {
            try {
                ECHandlerHelper.removeCallbacksRunnOnUI(initRunnable);
                ECPreferences.savePreference(
                        ECPreferenceSettings.SETTINGS_FULLY_EXIT, false, true);
                ContactsCache.getInstance().stop();
                CCPAppManager.setClientUser(null);
                ECDevice.unInitial();
                finish();

                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);

                return;
            } catch (InvalidClassException e) {
                e.printStackTrace();
            }
        }
//        if (mPager == null) {
            String account = getAutoRegistAccount();
            if (TextUtils.isEmpty(account)) {
                startActivity(new Intent(this, LoginActivity.class));
                finish();
                return;
            }
            // 注册第一次登陆同步消息
            registerReceiver(new String[] {
                    IMChattingHelper.INTENT_ACTION_SYNC_MESSAGE,
                    SDKCoreHelper.ACTION_SDK_CONNECT });
            ClientUser user = new ClientUser("").from(account);
            CCPAppManager.setClientUser(user);
            if (!ContactSqlManager.hasContact(user.getUserId())) {
                ECContacts contacts = new ECContacts();
                contacts.setClientUser(user);
                ContactSqlManager.insertContact(contacts);
            }

            if (SDKCoreHelper.getConnectState() != ECDevice.ECConnectState.CONNECT_SUCCESS
                    && !SDKCoreHelper.isKickOff()) {

                ContactsCache.getInstance().load();

                if(!TextUtils.isEmpty(getAutoRegistAccount())){
                    SDKCoreHelper.init(this);
                }
            }
            // 初始化主界面Tab资源
            if (!mInit) {
                initLauncherUIView();
            }
//        }
        OnUpdateMsgUnreadCounts();
        getTopContacts();
    }

    private void getTopContacts(){

        final ArrayList<String> arrayList = ConversationSqlManager.getInstance().qureyAllSession();
        ECChatManager chatManager =ECDevice.getECChatManager();
        if(chatManager ==null){
            return;
        }
        chatManager.getSessionsOfTop(new ECChatManager.OnGetSessionsOfTopListener() {
            @Override
            public void onGetSessionsOfTopResult(ECError error, String[] sessionsArr) {
                if (error.errorCode == SdkErrorCode.REQUEST_SUCCESS) {
                    for (String item : sessionsArr) {
                        ConversationSqlManager.updateSessionToTop(item, true);
                    }
                    List<String> list = Arrays.asList(sessionsArr);
                    for (String a : arrayList) {
                        if (!list.contains(a)) {
                            ConversationSqlManager.updateSessionToTop(a, false);
                        }
                    }
                }
            }
        });
    }

    public void handlerKickOff(String kickoffText) {
        if (isFinishing()) {
            return;
        }
        kickoffText = "Your account is logged on other devices. If it is not your operation, your password may have been leaked, please re login as soon as possible to change the password.";
        ECAlertDialog buildAlert = ECAlertDialog.buildAlert(this, kickoffText,
                getString(R.string.dialog_btn_confim),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ECNotificationManager.getInstance()
                                .forceCancelNotification();
                        restartAPP();
                    }
                });
        buildAlert.setTitle("Warning");
        buildAlert.setCanceledOnTouchOutside(false);
        buildAlert.setCancelable(false);
        buildAlert.show();
    }

    public void restartAPP() {

        ECDevice.unInitial();
        Intent intent = new Intent(this, VoiceChatLoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

}
